import { defineStore } from 'pinia'
import type { IAddressemit } from '../types/type'
import { Toast } from 'vant';

export const useAddressList = defineStore('AddressList', {
    state() {
        return {
            list: [] as Array<IAddressemit>,
            addEmit: {
                name: '',
                isDefault: false,
                postalCode: '',
                tel: '',
                address: '',
            },
            num: 0
        }
    },
    actions: {
        init() {
            this.addEmit.name = ''
            this.addEmit.address = ''

        },
        add(address: IAddressemit) {
            if (this.list.length === 0) {
                this.list.push(address)
                Toast.success('保存成功');
                return
            }
            let oldAddress: any=this.list.find((item)=>item.id===address.id)
            
            if (oldAddress) {
                oldAddress.name = address.name
                oldAddress.isDefault = address.isDefault
                oldAddress.postalCode = address.postalCode
                oldAddress.tel = address.tel
                oldAddress.address = address.address

                console.log('oldAddress.name', oldAddress.name)
                console.log('address.name', address.name)
                console.log('address', address)
            } else {
                this.list.push(address)
            }
            
            Toast.success('保存成功');
        },
        newAdd() {

        },
        useAddressEmit(address: any) {
            this.addEmit = address
        },
        numAdd() {
            return this.num++
        }
    },
    persist: {
        enabled: true, //允许存储,默认true
        strategies: [
            {
                key: 'caAddressListrt', //存储的数据名字
                storage: localStorage, //保存的类型，默认是session,
                paths: ['list', 'addEmit'], //需要持久保存的state里面的数据
            },
        ],
    },
})
